package seriver;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dao.BaseDao;
import dao.tbldao;
import enily.tbl;


public class tblimpl extends BaseDao implements tbldao {

	@Override
	public List<tbl> getID() {
		List<tbl> list = new ArrayList<>();
		String sql = "select * from tbl";
		ResultSet rs = super.executeQuery(sql);
		try {
			while (rs.next()) {
				tbl t = new tbl();
				t.setId(rs.getInt("id"));
				t.setMessage(rs.getString("message"));
				t.setAuthor(rs.getString("author"));
				t.setPostTime(rs.getDate("posttime"));
				
				list.add(t);
			}
		} catch (SQLException e){
			e.printStackTrace();
		} finally {
			try {
				super.closeAll(rs.getStatement().getConnection(), rs.getStatement(), rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	@Override
	public int add(tbl id) {
		String sql = "insert into tbl(message,author,posttime) values (?,?,?)";
		return super.executeUpdate(sql,id.getMessage(),id.getAuthor(),id.getPostTime());
	}
	public int getCount() {
		String sql = "select count(1) c from tbl";
		ResultSet rs = super.executeQuery(sql);
		int total = 0;
		try {
			if (rs.next()) {
				total = rs.getInt("c");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				super.closeAll(rs.getStatement().getConnection(), rs.getStatement(), rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return total;
	}

	@Override
	public List<tbl> getall(int page, int size) {
		List<tbl> list = new ArrayList<>();
		String sql = "select * from tbl limit ?,?";
	List<Object> params=new ArrayList<>();
	int start=(page - 1)*size;
	params.add(start);
	params.add(size);
	ResultSet rs=super.executeQuery(sql, params.toArray());
	try {
		while(rs.next()) {
			tbl t=new tbl();
			t.setId(rs.getInt("id"));
			t.setMessage(rs.getString("message"));
			t.setAuthor(rs.getString("author"));
			t.setPostTime(rs.getDate("posttime"));
			
			list.add(t);
		}
	} catch (SQLException e) {
		// TODO: handle exception
		e.printStackTrace();
	}
	return list;
		
	}

}
